package com.jizhi.onework.framework.context;

import com.jizhi.onework.dao.UserMapper;
import com.jizhi.onework.dataobj.vo.UserVO;
import com.jizhi.onework.pojo.User;

/**
 * 当前访问的操作环境
 * <p>
 * 对于 增、删、改场景，默认 Facade 接口中的每一个方法都应该包含 OperationContext 参数
 * <p>
 * 对于需要进行数据操作校验的场景也需要包含 OperationContext 参数
 *
 * @author hzhang7
 */
public class OperationContextHolder {

    private final static ThreadLocal<OperationContext> currentOperationContext = new ThreadLocal<>();

    public static OperationContext get() {
        return currentOperationContext.get();
    }

    public static void set(OperationContext context) {
        currentOperationContext.set(context);
    }

    /**
     * 清理资源
     */
    public static void clear() {
        currentOperationContext.remove();
    }

    /**
     * 手动构建 context
     *
     * @param userMapper
     * @param userId
     * @return
     */
    public static OperationContext build(UserMapper userMapper, long userId) {
        OperationContext context = new OperationContext();
        User userDO = userMapper.selectByPrimaryKey(userId);
        context.setUser(new UserVO(userDO));
        return context;
    }
}